<?php

namespace backend\controllers;

use Yii;
use backend\models\Event;
use backend\models\EventSearch;
use backend\models\EventType;
use backend\models\EventPrice;
use backend\models\ParseOnlineSaleForm;
use backend\models\ParseOfflineSaleForm;
use backend\models\TicketSales;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use Da\User\Filter\AccessRuleFilter;
use yii\data\ActiveDataProvider;
use backend\helpers\TicketSalesHelper;
/**
 * EventController implements the CRUD actions for Event model.
 */
class EventController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'ruleConfig' => [
                    'class' => AccessRuleFilter::class,
                ],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'view', 'view-full-information', 'view-sales'],
                        'roles' => ['browseEvent'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['create', 'parse-online-sale', 'parse-offline-sale'],
                        'roles' => ['createEvent'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['update'],
                        'roles' => ['updateEvent'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['delete', 'delete-image'],
                        'roles' => ['deleteEvent'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Event models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new EventSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Event model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionViewFullInformation($id)
    {
        return $this->render('view-full-information', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionViewSales($id)
    {
        $model = $this->findModel($id);

        $salesDataProvider = new ActiveDataProvider([
            'query' => $model->getSales(),
        ]);

        return $this->render('view-sales', [
            'model' => $model,
            'salesDataProvider' => $salesDataProvider,
        ]);
    }

    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionParseOnlineSale($id_event)
    {
        $model = new ParseOnlineSaleForm;
        
        if (Yii::$app->request->isPost) {

            $model->file = UploadedFile::getInstance($model, 'file');
            
            
            $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($model->file->tempName);
            $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($model->file->tempName);
                    
            $transaction = Yii::$app->db->beginTransaction();
            try {

                $num=$objPHPExcel->getSheetCount();//get number of sheets

                for($i = 0 ; $i < $num ; $i++)
                {
                    $sheet = $objPHPExcel->getSheet($i);
                    $highestRow = $sheet->getHighestRow();
                    $highestColumn = $sheet->getHighestColumn();
                                    
                    //$row is start 2 because first row assigned for heading.         
                    for($row=2; $row<=$highestRow; ++$row)
                    {
                        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                        $emptyRow = true;
                        foreach($rowData as $k => $v)
                        {
                            if($v)
                            {
                                $emptyRow = false;
                            }
                        }
                        if($emptyRow)
                        {
                            break; //this can be changed to continute to allow blank row in the excelsheet, otherwise loop will be terminated if blank row is found.
                        }

                        if($rowData[0][3] != '')
                        {
                            $ticketSale = new TicketSales;
                            $ticketSale->event_id = $id_event;
                            $ticketSale->date_sale = \DateTimeImmutable::createFromFormat('d.m.Y H:i', $rowData[0][3])->format('Y-m-d H:i:s');

                            if($rowData[0][1] != '')
                            {
                                $ticketSale->is_cancell = 1;
                            }
                            else
                            {
                                $ticketSale->is_cancell = 0;
                            }

                            if($rowData[0][5] == '')
                            {
                                $ticketSale->is_refund = 0;
                            }
                            else
                            {
                                $ticketSale->is_refund = 1;
                            }

                            $ticketSale->tariff = $rowData[0][2];
                            $ticketSale->selling_platform = $rowData[0][4];
                            $ticketSale->payment_method = $rowData[0][6];
                            $ticketSale->ticket_number = $rowData[0][0];
                            $ticketSale->is_online_sale = TicketSales::ONLINE_SALE;
                            $ticketSale->save(false);
                        }
                    }
                }
                $transaction->commit();
            }
            catch(\Exception $e) {
                $transaction->rollBack();
                throw $e;
            } catch(\Throwable $e) {
                $transaction->rollBack();
                throw $e;
            }
        }

        return $this->render('parse-online-sale', [
            'model' => $model,
        ]);
    }

    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionParseOfflineSale($id_event)
    {      
        $model = new ParseOfflineSaleForm;
        
        if (Yii::$app->request->isPost) {
            
            $model->load(Yii::$app->request->post());
            $model->file = UploadedFile::getInstance($model, 'file');

            $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($model->file->tempName);
            $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($model->file->tempName);
                    
            $transaction = Yii::$app->db->beginTransaction();

            try {

                $num=$objPHPExcel->getSheetCount();//get number of sheets

                for($i = 0 ; $i < $num ; $i++)
                {
                    $sheet = $objPHPExcel->getSheet($i);
                    $highestRow = $sheet->getHighestRow();
                    $highestColumn = $sheet->getHighestColumn();
                                    
                    //$row is start 2 because first row assigned for heading.         
                    for($row=1; $row<=$highestRow; ++$row)
                    {
                        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                        $emptyRow = true;
                        foreach($rowData as $k => $v)
                        {
                            if($v)
                            {
                                $emptyRow = false;
                            }
                        }
                        if($emptyRow)
                        {
                            break; //this can be changed to continute to allow blank row in the excelsheet, otherwise loop will be terminated if blank row is found.
                        }

                        $ticketNumbersArr = TicketSalesHelper::generateTicketNumber($rowData[0][1]);

                        foreach($ticketNumbersArr as $ticketNumber)
                        {
                            $ticketSale = new TicketSales;
                            $ticketSale->event_id = $id_event;
                            $ticketSale->date_sale = $model->date_start;
                            $ticketSale->is_cancell = 1;
                            $ticketSale->is_refund = 0;
                            $ticketSale->tariff = (float)$rowData[0][0];
                            $ticketSale->selling_platform = 'офлайн касса музея';
                            $ticketSale->payment_method = $rowData[0][2];
                            $ticketSale->ticket_number = $ticketNumber;
                            $ticketSale->is_online_sale = TicketSales::OFFLINE_SALE;
                            $ticketSale->save(false);
                        }
                    }
                }
                $transaction->commit();
            }
            catch(\Exception $e) {
                $transaction->rollBack();
                throw $e;
            } catch(\Throwable $e) {
                $transaction->rollBack();
                throw $e;
            }
        }
        
        return $this->render('parse-offline-sale', [
            'model' => $model,
        ]);

    }

    /**
     * Creates a new Event model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Event();
        $types = EventType::find()->select(['title', 'id'])->indexBy('id')->column();
        $prices = EventPrice::find()->select(['title', 'id'])->indexBy('id')->column();

        if ($model->load(Yii::$app->request->post())) {
            
            $model->imageForCover = UploadedFile::getInstance($model, 'imageForCover');
            $model->imagesForGallery = UploadedFile::getInstances($model, 'imagesForGallery');

            if($model->validate())
            {
                //$model->processAllImages();
                if($model->save(false))
                {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        }

        
        return $this->render('create', [
            'model' => $model,
            'types' => $types,
            'prices' => $prices,
        ]);
    }

    /**
     * Updates an existing Event model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $types = EventType::find()->select(['title', 'id'])->indexBy('id')->column();
        $prices = EventPrice::find()->select(['title', 'id'])->indexBy('id')->column();

        if ($model->load(Yii::$app->request->post())) {

            $model->imageForCover = UploadedFile::getInstance($model, 'imageForCover');
            $model->imagesForGallery = UploadedFile::getInstances($model, 'imagesForGallery');

            if($model->validate())
            {
                // if(!empty($model->imageForCover))
                // {
                //     $model->processCoverImage();
                // }
                // if(!empty($model->imagesForGallery))
                // {
                    
                // }
                //$model->processAllImages();
                if($model->save(false))
                {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        }

        return $this->render('update', [
            'model' => $model,
            'types' => $types,
            'prices' => $prices,
        ]);
    }

    /**
     * Deletes an existing Event model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionDeleteImage($id, $image_name)
    {
        $model = $this->findModel($id);

        $model->deleteImageFromGallery($image_name);

        if($model->save())
        {
            return $this->redirect(['update', 'id' => $id]);
        }

    }

    /**
     * Finds the Event model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Event the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Event::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
